package com.gym.controller.action.admin;

import java.sql.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.gym.model.dao.ConnessioneException;
import com.gym.model.dao.DAOCustomer;
import com.gym.model.dao.DAOUser;
import com.gym.model.dao.DatoNonTrovatoException;
import com.gym.model.dao.MetodoDaoException;
import com.gym.model.dao.ViolazioneIntegritaException;
import com.gym.model.entity.Customer;
import com.gym.model.entity.User;

public class UpdateCustomer extends Action{

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String code=request.getParameter("code");
		String idUser=request.getParameter("idUser");
		String firstname=request.getParameter("firstname");
		String lastname=request.getParameter("lastname");
		char gender=request.getParameter("gender").charAt(0);
		String fc=request.getParameter("fc");
		String phone=request.getParameter("phone");
		Date bdate=java.sql.Date.valueOf(request.getParameter("bdate")); 
		String date=request.getParameter("cdatexpiry");
		Date cdate=null; //TODO verificare il valore quando non viene settato nessun valore
		if(!date.equals(" "))
		{
			cdate=java.sql.Date.valueOf(date);	
			System.out.println("passata data: "+cdate);
		}
		try {
			DAOUser duser = new DAOUser();
			User user=duser.select(Integer.parseInt(idUser));
			Customer customer=new Customer(code, firstname, lastname, gender, fc, phone, bdate, cdate, null, user);
			DAOCustomer dao = new DAOCustomer();
			dao.update(customer);
			request.setAttribute("feedback", "OK, modificato il customer "+firstname+" "+lastname);
			return mapping.findForward("success");
		}
		catch(ConnessioneException | MetodoDaoException | DatoNonTrovatoException | ViolazioneIntegritaException e)	{
			request.setAttribute("error", e.getMessage());
			return mapping.findForward("failure"); 
		}
		
	}

}
